// 夸克网盘文件管理器 JavaScript
class QuarkFileManager {
    constructor() {
        this.apiBaseUrl = '/api/quark';
        this.currentFolderId = '0';
        this.currentPage = 1;
        this.pageSize = 20;
        this.currentView = 'list';
        this.selectedFiles = new Set();
        this.fileList = [];
        this.totalCount = 0;
        this.totalPages = 0;
        this.cookie = '';
        this.eagleeyeTraceid = '0bf8fe6317578302780796642ee7a1';
        this.breadcrumb = [{ fid: '0', name: '根目录' }];
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadSettings();
        
        // 检查是否有Cookie，如果没有则显示设置提示
        if (!this.cookie) {
            this.showMessage('请先设置夸克网盘Cookie才能使用', 'info');
            this.showSettingsModal();
        } else {
            this.loadFileList();
        }
    }

    bindEvents() {
        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', () => {
            this.loadFileList();
        });

        // 设置按钮
        document.getElementById('settingsBtn').addEventListener('click', () => {
            this.showSettingsModal();
        });

        // 搜索功能
        document.getElementById('searchInput').addEventListener('input', (e) => {
            this.debounce(() => {
                this.searchFiles(e.target.value);
            }, 300)();
        });

        // 文件夹选择
        document.getElementById('folderSelect').addEventListener('change', (e) => {
            this.currentFolderId = e.target.value;
            this.currentPage = 1;
            this.loadFileList();
        });

        // 页面大小选择
        document.getElementById('pageSizeSelect').addEventListener('change', (e) => {
            this.pageSize = parseInt(e.target.value);
            this.currentPage = 1;
            this.loadFileList();
        });

        // 排序选择
        document.getElementById('sortSelect').addEventListener('change', (e) => {
            this.sortFiles(e.target.value);
        });

        // 视图切换
        document.getElementById('listViewBtn').addEventListener('click', () => {
            this.switchView('list');
        });

        document.getElementById('gridViewBtn').addEventListener('click', () => {
            this.switchView('grid');
        });

        // 全选按钮
        document.getElementById('selectAllBtn').addEventListener('click', () => {
            this.toggleSelectAll();
        });

        // 下载选中文件
        document.getElementById('downloadSelectedBtn').addEventListener('click', () => {
            this.downloadSelectedFiles();
        });

        // 删除选中文件
        document.getElementById('deleteSelectedBtn').addEventListener('click', () => {
            this.deleteSelectedFiles();
        });

        // 分页按钮
        document.getElementById('prevPageBtn').addEventListener('click', () => {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.loadFileList();
            }
        });

        document.getElementById('nextPageBtn').addEventListener('click', () => {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
                this.loadFileList();
            }
        });

        // 模态框事件
        this.bindModalEvents();
    }

    bindModalEvents() {
        console.log('开始绑定模态框事件');
        
        // 设置模态框
        const settingsModal = document.getElementById('settingsModal');
        const settingsClose = settingsModal.querySelector('.modal-close');
        const saveSettingsBtn = document.getElementById('saveSettingsBtn');
        const cancelSettingsBtn = document.getElementById('cancelSettingsBtn');

        settingsClose.addEventListener('click', () => this.hideModal('settingsModal'));
        cancelSettingsBtn.addEventListener('click', () => this.hideModal('settingsModal'));
        saveSettingsBtn.addEventListener('click', () => this.saveSettings());

        // 文件详情模态框
        const fileDetailModal = document.getElementById('fileDetailModal');
        const detailClose = fileDetailModal.querySelector('.modal-close');
        const closeDetailBtn = document.getElementById('closeDetailBtn');
        const downloadFileBtn = document.getElementById('downloadFileBtn');

        detailClose.addEventListener('click', () => this.hideModal('fileDetailModal'));
        closeDetailBtn.addEventListener('click', () => this.hideModal('fileDetailModal'));
        downloadFileBtn.addEventListener('click', () => this.downloadCurrentFile());

        // 重命名模态框
        const renameModal = document.getElementById('renameModal');
        const renameClose = renameModal.querySelector('.modal-close');
        const confirmRenameBtn = document.getElementById('confirmRenameBtn');
        const cancelRenameBtn = document.getElementById('cancelRenameBtn');

        renameClose.addEventListener('click', () => this.hideModal('renameModal'));
        cancelRenameBtn.addEventListener('click', () => this.hideModal('renameModal'));
        confirmRenameBtn.addEventListener('click', () => this.confirmRename());

        // 批量重命名模态框
        const batchRenameModal = document.getElementById('batchRenameModal');
        const batchRenameClose = batchRenameModal.querySelector('.modal-close');
        const batchRenameBtn = document.getElementById('batchRenameBtn');
        const exportFilesBtn = document.getElementById('exportFilesBtn');
        const importFile = document.getElementById('importFile');
        const startBatchRenameBtn = document.getElementById('startBatchRenameBtn');
        const cancelBatchRenameBtn = document.getElementById('cancelBatchRenameBtn');
        
        console.log('批量重命名按钮元素:', batchRenameBtn);

        batchRenameBtn.addEventListener('click', () => {
            console.log('批量重命名按钮被点击');
            this.showModal('batchRenameModal');
        });
        batchRenameClose.addEventListener('click', () => this.hideModal('batchRenameModal'));
        cancelBatchRenameBtn.addEventListener('click', () => this.hideModal('batchRenameModal'));
        exportFilesBtn.addEventListener('click', () => this.exportAllFiles());
        importFile.addEventListener('change', (e) => this.handleImportFile(e));
        startBatchRenameBtn.addEventListener('click', () => this.startBatchRename());

        // 标签页切换
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
        });

        // 点击模态框外部关闭
        [settingsModal, fileDetailModal, renameModal].forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.hideModal(modal.id);
                }
            });
        });
    }

    // 加载文件列表
    async loadFileList() {
        // 检查Cookie是否设置
        if (!this.cookie) {
            this.showMessage('请先设置夸克网盘Cookie', 'warning');
            this.showSettingsModal();
            return;
        }

        this.showLoading(true);
        
        try {
            // 构建请求URL
            const baseUrl = `${this.apiBaseUrl}/files`;
            const url = new URL(baseUrl, window.location.origin);
            url.searchParams.append('folderId', this.currentFolderId);
            url.searchParams.append('page', this.currentPage);
            url.searchParams.append('pageSize', this.pageSize);
            url.searchParams.append('cookie', this.cookie);
            url.searchParams.append('eagleeyeTraceid', this.eagleeyeTraceid);

            console.log('请求URL:', url.toString()); // 调试日志
            console.log('Cookie长度:', this.cookie.length); // 调试日志
            
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();

            if (data && data.data) {
                this.fileList = data.data.list || [];
                this.totalCount = data.data.metadata?.total || 0;
                this.totalPages = Math.ceil(this.totalCount / this.pageSize);
                
                this.renderFileList();
                this.updatePagination();
                this.updateBreadcrumb();
            } else {
                this.showMessage('加载文件列表失败', 'error');
                this.renderEmptyState();
            }
        } catch (error) {
            console.error('加载文件列表失败:', error);
            
            let errorMessage = '网络错误，请检查网络连接';
            if (error.message.includes('HTTP错误')) {
                errorMessage = error.message;
            } else if (error.message.includes('Failed to fetch')) {
                errorMessage = '无法连接到服务器，请检查服务器是否启动';
            } else if (error.message.includes('JSON')) {
                errorMessage = '服务器响应格式错误';
            }
            
            this.showMessage(errorMessage, 'error');
            this.renderEmptyState();
        } finally {
            this.showLoading(false);
        }
    }

    // 渲染文件列表
    renderFileList() {
        const fileListContainer = document.getElementById('fileList');
        const emptyState = document.getElementById('emptyState');
        
        if (this.fileList.length === 0) {
            fileListContainer.style.display = 'none';
            emptyState.style.display = 'block';
            return;
        }

        fileListContainer.style.display = 'block';
        emptyState.style.display = 'none';

        fileListContainer.innerHTML = this.fileList.map(file => this.createFileItem(file)).join('');
        
        // 绑定文件项事件
        this.bindFileItemEvents();
    }

    // 创建文件项HTML
    createFileItem(file) {
        const isSelected = this.selectedFiles.has(file.fid);
        const fileType = this.getFileType(file);
        const fileIcon = this.getFileIcon(fileType);
        const fileSize = this.formatFileSize(file.size);
        const createDate = this.formatDate(file.createdAt);
        const updateDate = this.formatDate(file.updatedAt);
        
        // 调试信息
        console.log('Creating file item:', {
            fileName: file.fileName,
            dir: file.dir,
            file: file.file,
            isDir: file.dir === true,
            isFile: file.dir === false
        });

        return `
            <div class="file-item ${this.currentView}-view ${isSelected ? 'selected' : ''}" data-fid="${file.fid}">
                <input type="checkbox" class="file-checkbox" ${isSelected ? 'checked' : ''} data-fid="${file.fid}">
                <div class="file-icon ${fileType}" data-type="${fileType}">
                    <i class="${fileIcon}"></i>
                </div>
                <div class="file-info">
                    <div class="file-name" title="${file.fileName}">${file.fileName}</div>
                    <div class="file-meta">
                        <span><i class="fas fa-weight-hanging"></i> ${fileSize}</span>
                        <span><i class="fas fa-calendar-plus"></i> ${createDate}</span>
                        <span><i class="fas fa-calendar-edit"></i> ${updateDate}</span>
                        ${file.dir ? '<span><i class="fas fa-folder"></i> 文件夹</span>' : ''}
                    </div>
                </div>
                <div class="file-actions">
                    <button class="file-action-btn" onclick="fileManager.viewFile('${file.fid}')" title="查看详情">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="file-action-btn" onclick="fileManager.showRenameModal('${file.fid}')" title="重命名">
                        <i class="fas fa-edit"></i>
                    </button>
                    $<button class="file-action-btn" onclick="fileManager.downloadFile('${file.fid}')" title="下载">
                        <i class="fas fa-download"></i>
                    </button>
                    ${file.dir === true ? `<button class="file-action-btn" onclick="fileManager.enterFolder('${file.fid}', '${file.fileName}')" title="进入文件夹">
                        <i class="fas fa-folder-open"></i>
                    </button>` : ''}
                </div>
            </div>
        `;
    }

    // 绑定文件项事件
    bindFileItemEvents() {
        // 文件项点击事件
        document.querySelectorAll('.file-item').forEach(item => {
            item.addEventListener('click', (e) => {
                if (e.target.type === 'checkbox' || e.target.closest('.file-action-btn')) {
                    return;
                }
                
                const fid = item.dataset.fid;
                const file = this.fileList.find(f => f.fid === fid);
                if (file) {
                    if (file.dir) {
                        this.enterFolder(fid, file.fileName);
                    } else {
                        this.viewFile(fid);
                    }
                }
            });
        });

        // 复选框事件
        document.querySelectorAll('.file-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const fid = e.target.dataset.fid;
                if (e.target.checked) {
                    this.selectedFiles.add(fid);
                } else {
                    this.selectedFiles.delete(fid);
                }
                this.updateSelectionUI();
            });
        });
    }

    // 进入文件夹
    enterFolder(fid, name) {
        this.currentFolderId = fid;
        this.currentPage = 1;
        this.selectedFiles.clear();
        
        // 更新面包屑
        this.breadcrumb.push({ fid, name });
        this.updateBreadcrumb();
        
        this.loadFileList();
    }

    // 更新面包屑导航
    updateBreadcrumb() {
        const breadcrumbContainer = document.querySelector('.breadcrumb');
        breadcrumbContainer.innerHTML = this.breadcrumb.map((item, index) => {
            const isLast = index === this.breadcrumb.length - 1;
            return `
                <span class="breadcrumb-item ${isLast ? 'active' : ''}" 
                      data-fid="${item.fid}" 
                      onclick="${!isLast ? `fileManager.navigateToFolder(${index})` : ''}">
                    ${index === 0 ? '<i class="fas fa-home"></i>' : ''} ${item.name}
                </span>
            `;
        }).join('');
    }

    // 导航到指定文件夹
    navigateToFolder(index) {
        this.breadcrumb = this.breadcrumb.slice(0, index + 1);
        this.currentFolderId = this.breadcrumb[index].fid;
        this.currentPage = 1;
        this.selectedFiles.clear();
        this.loadFileList();
    }

    // 查看文件详情
    viewFile(fid) {
        const file = this.fileList.find(f => f.fid === fid);
        if (!file) return;

        const detailContent = document.getElementById('fileDetailContent');
        detailContent.innerHTML = `
            <div class="file-detail">
                <div class="detail-header">
                    <div class="file-icon-large ${this.getFileType(file)}">
                        <i class="${this.getFileIcon(this.getFileType(file))}"></i>
                    </div>
                    <div class="file-info-large">
                        <h3>${file.fileName}</h3>
                        <p class="file-path">${this.getCurrentPath()}</p>
                    </div>
                </div>
                <div class="detail-info">
                    <div class="info-row">
                        <span class="info-label">文件ID:</span>
                        <span class="info-value">${file.fid}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">文件大小:</span>
                        <span class="info-value">${this.formatFileSize(file.size)}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">文件类型:</span>
                        <span class="info-value">${file.formatType || '未知'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">创建时间:</span>
                        <span class="info-value">${this.formatDate(file.createdAt)}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">修改时间:</span>
                        <span class="info-value">${this.formatDate(file.updatedAt)}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">文件来源:</span>
                        <span class="info-value">${file.source || '未知'}</span>
                    </div>
                </div>
            </div>
        `;

        this.currentFile = file;
        this.showModal('fileDetailModal');
    }

    // 下载文件
    downloadFile(fid) {
        const file = this.fileList.find(f => f.fid === fid);
        if (!file) return;

        if (file.downloadUrl) {
            window.open(file.downloadUrl, '_blank');
            this.showMessage(`开始下载: ${file.fileName}`, 'success');
        } else {
            this.showMessage('下载链接不可用', 'error');
        }
    }

    // 下载当前文件（从详情模态框）
    downloadCurrentFile() {
        if (this.currentFile) {
            this.downloadFile(this.currentFile.fid);
            this.hideModal('fileDetailModal');
        }
    }

    // 下载选中的文件
    downloadSelectedFiles() {
        if (this.selectedFiles.size === 0) {
            this.showMessage('请先选择要下载的文件', 'warning');
            return;
        }

        const selectedFileList = Array.from(this.selectedFiles).map(fid => 
            this.fileList.find(f => f.fid === fid)
        ).filter(f => f && !f.dir);

        if (selectedFileList.length === 0) {
            this.showMessage('选中的文件中没有可下载的文件', 'warning');
            return;
        }

        selectedFileList.forEach(file => {
            if (file.downloadUrl) {
                window.open(file.downloadUrl, '_blank');
            }
        });

        this.showMessage(`开始下载 ${selectedFileList.length} 个文件`, 'success');
    }

    // 删除选中的文件
    deleteSelectedFiles() {
        if (this.selectedFiles.size === 0) {
            this.showMessage('请先选择要删除的文件', 'warning');
            return;
        }

        if (confirm(`确定要删除选中的 ${this.selectedFiles.size} 个文件吗？此操作不可恢复！`)) {
            // 这里应该调用删除API，目前只是模拟
            this.showMessage('删除功能暂未实现，请联系管理员', 'info');
        }
    }

    // 切换全选
    toggleSelectAll() {
        const allCheckboxes = document.querySelectorAll('.file-checkbox');
        const allChecked = Array.from(allCheckboxes).every(cb => cb.checked);
        
        allCheckboxes.forEach(checkbox => {
            checkbox.checked = !allChecked;
            const fid = checkbox.dataset.fid;
            if (!allChecked) {
                this.selectedFiles.add(fid);
            } else {
                this.selectedFiles.delete(fid);
            }
        });
        
        this.updateSelectionUI();
    }

    // 更新选择状态UI
    updateSelectionUI() {
        const selectAllBtn = document.getElementById('selectAllBtn');
        const downloadBtn = document.getElementById('downloadSelectedBtn');
        const deleteBtn = document.getElementById('deleteSelectedBtn');
        
        const selectedCount = this.selectedFiles.size;
        const hasSelection = selectedCount > 0;
        
        selectAllBtn.innerHTML = hasSelection ? 
            `<i class="fas fa-square"></i> 取消全选` : 
            `<i class="fas fa-check-square"></i> 全选`;
        
        downloadBtn.disabled = !hasSelection;
        deleteBtn.disabled = !hasSelection;
        
        // 更新选中状态样式
        document.querySelectorAll('.file-item').forEach(item => {
            const fid = item.dataset.fid;
            if (this.selectedFiles.has(fid)) {
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }

    // 切换视图
    switchView(view) {
        this.currentView = view;
        const fileList = document.getElementById('fileList');
        const listBtn = document.getElementById('listViewBtn');
        const gridBtn = document.getElementById('gridViewBtn');
        
        fileList.className = `file-list ${view}-view`;
        listBtn.classList.toggle('active', view === 'list');
        gridBtn.classList.toggle('active', view === 'grid');
        
        // 重新渲染文件列表以应用新视图
        this.renderFileList();
    }

    // 搜索文件
    searchFiles(keyword) {
        if (!keyword.trim()) {
            this.renderFileList();
            return;
        }

        const filteredFiles = this.fileList.filter(file => 
            file.fileName.toLowerCase().includes(keyword.toLowerCase())
        );

        const fileListContainer = document.getElementById('fileList');
        fileListContainer.innerHTML = filteredFiles.map(file => this.createFileItem(file)).join('');
        this.bindFileItemEvents();
    }

    // 排序文件
    sortFiles(sortType) {
        const sortedFiles = [...this.fileList].sort((a, b) => {
            switch (sortType) {
                case 'name':
                    return a.fileName.localeCompare(b.fileName);
                case 'size':
                    return b.size - a.size;
                case 'date':
                    return b.updatedAt - a.updatedAt;
                case 'type':
                    return (a.formatType || '').localeCompare(b.formatType || '');
                default:
                    return 0;
            }
        });

        this.fileList = sortedFiles;
        this.renderFileList();
    }

    // 更新分页
    updatePagination() {
        const prevBtn = document.getElementById('prevPageBtn');
        const nextBtn = document.getElementById('nextPageBtn');
        const pageNumbers = document.getElementById('pageNumbers');
        const paginationInfo = document.getElementById('paginationInfo');

        // 更新按钮状态
        prevBtn.disabled = this.currentPage <= 1;
        nextBtn.disabled = this.currentPage >= this.totalPages;

        // 更新分页信息
        const start = (this.currentPage - 1) * this.pageSize + 1;
        const end = Math.min(this.currentPage * this.pageSize, this.totalCount);
        paginationInfo.textContent = `显示 ${start}-${end} 条，共 ${this.totalCount} 条`;

        // 生成页码按钮
        pageNumbers.innerHTML = '';
        const maxVisiblePages = 5;
        let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-number ${i === this.currentPage ? 'active' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                this.currentPage = i;
                this.loadFileList();
            });
            pageNumbers.appendChild(pageBtn);
        }
    }

    // 显示/隐藏加载状态
    showLoading(show) {
        const spinner = document.getElementById('loadingSpinner');
        const fileList = document.getElementById('fileList');
        
        if (show) {
            spinner.style.display = 'block';
            fileList.style.display = 'none';
        } else {
            spinner.style.display = 'none';
            fileList.style.display = 'block';
        }
    }

    // 显示/隐藏空状态
    renderEmptyState() {
        const fileList = document.getElementById('fileList');
        const emptyState = document.getElementById('emptyState');
        
        fileList.style.display = 'none';
        emptyState.style.display = 'block';
    }

    // 显示模态框
    showModal(modalId) {
        const modal = document.getElementById(modalId);
        modal.classList.add('show');
        modal.style.display = 'flex';
    }

    // 隐藏模态框
    hideModal(modalId) {
        const modal = document.getElementById(modalId);
        modal.classList.remove('show');
        modal.style.display = 'none';
    }

    // 显示设置模态框
    showSettingsModal() {
        document.getElementById('cookieInput').value = this.cookie;
        document.getElementById('traceIdInput').value = this.eagleeyeTraceid;
        this.showModal('settingsModal');
    }

    // 保存设置
    saveSettings() {
        this.cookie = document.getElementById('cookieInput').value.trim();
        this.eagleeyeTraceid = document.getElementById('traceIdInput').value.trim();

        if (!this.cookie) {
            this.showMessage('请输入夸克网盘Cookie', 'error');
            return;
        }

        // 验证Cookie格式
        if (!this.validateCookie(this.cookie)) {
            this.showMessage('Cookie格式不正确，请检查是否包含必要的字段', 'warning');
            return;
        }

        // 保存到本地存储
        localStorage.setItem('quarkCookie', this.cookie);
        localStorage.setItem('quarkTraceId', this.eagleeyeTraceid);

        this.hideModal('settingsModal');
        this.showMessage('设置保存成功，正在测试连接...', 'success');
        
        // 清空当前文件列表
        this.fileList = [];
        this.selectedFiles.clear();
        this.currentPage = 1;
        
        // 先测试连接，然后加载文件列表
        this.testConnection().then(() => {
            this.loadFileList();
        }).catch((error) => {
            this.showMessage('连接测试失败: ' + error.message, 'error');
        });
    }

    // 验证Cookie格式
    validateCookie(cookie) {
        if (!cookie || cookie.length < 10) {
            return false;
        }
        
        // 检查是否包含夸克网盘的关键Cookie字段
        const requiredFields = ['b-user-id', '__sdid', '_UP_D_'];
        return requiredFields.some(field => cookie.includes(field));
    }

    // 测试连接
    async testConnection() {
        try {
            const url = new URL(`${this.apiBaseUrl}/info`, window.location.origin);
            console.log('测试连接URL:', url.toString());
            
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`服务器响应错误: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.text();
            console.log('连接测试成功:', data);
            return true;
        } catch (error) {
            console.error('连接测试失败:', error);
            throw error;
        }
    }

    // 加载设置
    loadSettings() {
        this.cookie = localStorage.getItem('quarkCookie') || '';
        this.eagleeyeTraceid = localStorage.getItem('quarkTraceId') || '0bf8fe6317578302780796642ee7a1';
    }

    // 显示消息提示
    showMessage(message, type = 'info') {
        const toast = document.getElementById('messageToast');
        const icon = toast.querySelector('.toast-icon');
        const messageEl = toast.querySelector('.toast-message');

        // 设置图标
        const icons = {
            success: 'fas fa-check',
            error: 'fas fa-times',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };

        icon.className = `toast-icon ${icons[type] || icons.info}`;
        messageEl.textContent = message;

        // 显示提示
        toast.className = `toast ${type} show`;
        
        // 3秒后自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // 工具方法
    getFileType(file) {
        if (file.dir) return 'folder';
        
        const ext = file.fileName.split('.').pop()?.toLowerCase();
        const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
        const videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'];
        const audioExts = ['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a'];
        const docExts = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'];
        const archiveExts = ['zip', 'rar', '7z', 'tar', 'gz'];
        const codeExts = ['js', 'html', 'css', 'java', 'py', 'cpp', 'c', 'php'];

        if (imageExts.includes(ext)) return 'image';
        if (videoExts.includes(ext)) return 'video';
        if (audioExts.includes(ext)) return 'audio';
        if (docExts.includes(ext)) return 'document';
        if (archiveExts.includes(ext)) return 'archive';
        if (codeExts.includes(ext)) return 'code';
        
        return 'default';
    }

    getFileIcon(fileType) {
        const icons = {
            folder: 'fas fa-folder',
            image: 'fas fa-image',
            video: 'fas fa-video',
            audio: 'fas fa-music',
            document: 'fas fa-file-alt',
            archive: 'fas fa-file-archive',
            code: 'fas fa-code',
            default: 'fas fa-file'
        };
        return icons[fileType] || icons.default;
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    formatDate(timestamp) {
        if (!timestamp) return '未知';
        const date = new Date(timestamp * 1000);
        return date.toLocaleString('zh-CN');
    }

    getCurrentPath() {
        return this.breadcrumb.map(item => item.name).join(' / ');
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 显示重命名模态框
    showRenameModal(fid) {
        console.log('showRenameModal called with fid:', fid);
        
        const file = this.fileList.find(f => f.fid === fid);
        if (!file) {
            console.error('File not found with fid:', fid);
            this.showMessage('文件未找到', 'error');
            return;
        }

        console.log('Found file:', file);

        // 分离文件名和扩展名
        const lastDotIndex = file.fileName.lastIndexOf('.');
        const fileName = lastDotIndex > 0 ? file.fileName.substring(0, lastDotIndex) : file.fileName;
        const fileExtension = lastDotIndex > 0 ? file.fileName.substring(lastDotIndex) : '';

        console.log('File name parts:', { fileName, fileExtension });

        // 填充表单
        document.getElementById('currentFileName').value = file.fileName;
        document.getElementById('newFileName').value = fileName;
        document.getElementById('fileExtension').value = fileExtension;

        // 保存当前文件信息
        this.renameFile = file;

        console.log('Showing rename modal');
        this.showModal('renameModal');
    }


    // 确认重命名
    async confirmRename() {
        console.log('confirmRename called');
        
        if (!this.renameFile) {
            console.error('No rename file set');
            this.showMessage('没有选择要重命名的文件', 'error');
            return;
        }

        const newFileName = document.getElementById('newFileName').value.trim();
        const fileExtension = document.getElementById('fileExtension').value;

        console.log('Form values:', { newFileName, fileExtension });

        if (!newFileName) {
            this.showMessage('请输入新文件名', 'error');
            return;
        }

        const fullNewFileName = newFileName + fileExtension;

        if (fullNewFileName === this.renameFile.fileName) {
            this.showMessage('新文件名与当前文件名相同', 'warning');
            return;
        }

        try {
            this.showMessage('正在重命名文件...', 'info');
            
            // 构建请求URL
            const url = new URL(`${this.apiBaseUrl}/rename`, window.location.origin);
            url.searchParams.append('fid', this.renameFile.fid);
            url.searchParams.append('fileName', fullNewFileName);
            url.searchParams.append('cookie', this.cookie);
            url.searchParams.append('eagleeyeTraceid', this.eagleeyeTraceid);

            console.log('重命名请求URL:', url.toString());
            console.log('重命名参数:', {
                fid: this.renameFile.fid,
                fileName: fullNewFileName,
                cookieLength: this.cookie.length,
                eagleeyeTraceid: this.eagleeyeTraceid
            });

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
            }

            const result = await response.text();
            console.log('重命名响应:', result);

            this.hideModal('renameModal');
            this.showMessage(`文件重命名成功: ${fullNewFileName}`, 'success');
            
            // 更新本地文件列表中的文件名
            this.renameFile.fileName = fullNewFileName;
            
            // 重新渲染文件列表
            this.renderFileList();
            
        } catch (error) {
            console.error('重命名文件失败:', error);
            this.showMessage('重命名失败: ' + error.message, 'error');
        }
    }
}

// 初始化文件管理器
let fileManager;
document.addEventListener('DOMContentLoaded', () => {
    fileManager = new QuarkFileManager();
});

// 添加一些额外的CSS样式到页面
const additionalStyles = `
<style>
.file-detail {
    padding: 20px 0;
}

.detail-header {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e9ecef;
}

.file-icon-large {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32px;
    color: white;
}

.file-info-large h3 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 24px;
}

.file-path {
    color: #6c757d;
    margin: 0;
    font-size: 14px;
}

.detail-info {
    display: grid;
    gap: 15px;
}

.info-row {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f8f9fa;
}

.info-label {
    font-weight: 600;
    color: #495057;
    min-width: 100px;
    margin-right: 15px;
}

.info-value {
    color: #6c757d;
    word-break: break-all;
}
</style>
`;

document.head.insertAdjacentHTML('beforeend', additionalStyles);

// 批量重命名相关方法
QuarkFileManager.prototype.switchTab = function(tabName) {
        // 切换标签页
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        document.getElementById(`${tabName}Tab`).classList.add('active');
    };

// 导出所有文件
QuarkFileManager.prototype.exportAllFiles = async function() {
        if (!this.cookie) {
            this.showMessage('请先设置Cookie', 'error');
            return;
        }

        try {
            this.showMessage('正在导出文件列表，请稍候...', 'info');
            
            const url = new URL(`${this.apiBaseUrl}/export`, window.location.origin);
            url.searchParams.append('cookie', this.cookie);
            url.searchParams.append('eagleeyeTraceid', this.eagleeyeTraceid);

            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const excelData = await response.blob();
            
            // 创建下载链接
            const blob = new Blob([excelData], { 
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
            });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'quark_files.xlsx';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 显示导出结果
            document.getElementById('exportResult').style.display = 'block';
            this.showMessage('Excel文件导出成功！', 'success');
            
        } catch (error) {
            console.error('导出失败:', error);
            this.showMessage('导出失败: ' + error.message, 'error');
        }
    };

// 处理导入文件
QuarkFileManager.prototype.handleImportFile = function(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const csvData = e.target.result;
                const lines = csvData.split('\n');
                const headers = lines[0].split(',');
                
                // 查找必要的列
                const fidIndex = headers.findIndex(h => h.includes('文件ID'));
                const nameIndex = headers.findIndex(h => h.includes('文件名'));
                
                if (fidIndex === -1 || nameIndex === -1) {
                    this.showMessage('文件格式错误，请确保包含文件ID和文件名列', 'error');
                    return;
                }

                // 解析数据
                const renameData = [];
                for (let i = 1; i < lines.length; i++) {
                    const line = lines[i].trim();
                    if (!line) continue;
                    
                    const columns = this.parseCSVLine(line);
                    if (columns.length > Math.max(fidIndex, nameIndex)) {
                        renameData.push({
                            fid: columns[fidIndex],
                            oldName: columns[nameIndex],
                            newName: columns[nameIndex] // 初始时新旧名称相同
                        });
                    }
                }

                this.renameData = renameData;
                this.showImportPreview(renameData);
                
            } catch (error) {
                console.error('解析文件失败:', error);
                this.showMessage('解析文件失败: ' + error.message, 'error');
            }
        };
        
        reader.readAsText(file);
    };

// 解析CSV行（处理引号）
QuarkFileManager.prototype.parseCSVLine = function(line) {
        const result = [];
        let current = '';
        let inQuotes = false;
        
        for (let i = 0; i < line.length; i++) {
            const char = line[i];
            if (char === '"') {
                inQuotes = !inQuotes;
            } else if (char === ',' && !inQuotes) {
                result.push(current);
                current = '';
            } else {
                current += char;
            }
        }
        result.push(current);
        return result;
    };

// 显示导入预览
QuarkFileManager.prototype.showImportPreview = function(renameData) {
        const tbody = document.getElementById('previewTableBody');
        tbody.innerHTML = '';
        
        renameData.forEach((item, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.fid}</td>
                <td>${item.oldName}</td>
                <td>
                    <input type="text" value="${item.oldName}" 
                           onchange="fileManager.updateRenameData(${index}, this.value)"
                           style="width: 100%; padding: 4px; border: 1px solid #ddd; border-radius: 3px;">
                </td>
            `;
            tbody.appendChild(row);
        });
        
        document.getElementById('importPreview').style.display = 'block';
        document.getElementById('startBatchRenameBtn').style.display = 'inline-block';
    };

// 更新重命名数据
QuarkFileManager.prototype.updateRenameData = function(index, newName) {
        if (this.renameData && this.renameData[index]) {
            this.renameData[index].newName = newName;
        }
    };

// 开始批量重命名
QuarkFileManager.prototype.startBatchRename = async function() {
        if (!this.renameData || this.renameData.length === 0) {
            this.showMessage('没有可重命名的文件', 'error');
            return;
        }

        if (!this.cookie) {
            this.showMessage('请先设置Cookie', 'error');
            return;
        }

        try {
            this.showMessage('开始批量重命名，请稍候...', 'info');
            
            // 过滤出需要重命名的文件（新名称与原名称不同）
            const toRename = this.renameData.filter(item => item.newName !== item.oldName);
            
            if (toRename.length === 0) {
                this.showMessage('没有需要重命名的文件', 'info');
                return;
            }

            const url = new URL(`${this.apiBaseUrl}/batch-rename`, window.location.origin);
            url.searchParams.append('cookie', this.cookie);
            url.searchParams.append('eagleeyeTraceid', this.eagleeyeTraceid);

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(toRename)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.text();
            this.showMessage('批量重命名完成！', 'success');
            
            // 显示详细结果
            console.log('批量重命名结果:', result);
            
            // 刷新文件列表
            this.loadFileList();
            
            // 关闭模态框
            this.hideModal('batchRenameModal');
            
        } catch (error) {
            console.error('批量重命名失败:', error);
            this.showMessage('批量重命名失败: ' + error.message, 'error');
        }
    };